#!/usr/bin/env python

from twisted.internet import reactor
from twisted.spread import pb
from twisted.cred import checkers, portal
import twisted.web
import sys

from option import Option

Option().events = []

# Logging
import logging
import logging.handlers

Option().log = logging.getLogger('')
Option().log.setLevel(logging.DEBUG)
def printah(x): print x
h = logging.handlers.RotatingFileHandler('logs/remoteCube.txt', maxBytes = 1024*1024)
h.setLevel(logging.DEBUG)
format = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-12s %(message)s')
h.setFormatter(format)
Option().log.addHandler(h)

h = logging.StreamHandler()
h.setLevel(logging.DEBUG)
h.setFormatter(format)
Option().log.addHandler(h)

Option().chatLog = logging.getLogger('chat')


import users
Option().users = users.Users()

#import serverChat
#import serverWeb
import PBServer
import chat
Option().chat = chat.Chat()

# Authentication
PBportal = portal.Portal(PBServer.Realm())
import credentialChecker
PBportal.registerChecker(credentialChecker.CredentialChecker())

def start(title, port, factory):
	print 'Starting',title,'server ...',
	reactor.listenTCP(port, factory)
	print 'Done'

print '==--> REMOTE CUBE <--=='
from os.path import exists
if exists('config.cfg'):
	print 'Loading config...',
	import config
	config.load('config.cfg')
	print 'Done'

if exists('bootstrap.py'):
	print 'Bootstrapping...',
	execfile('bootstrap.py')
	print 'Done'



#start('telnet server', 1446, serverChat.ServerChatFactory())
start('PB server', 1447, pb.PBServerFactory(PBportal))
#start('web server', 1446, serverWeb.ServerWebFactory())

print 'Here we go!'
Option().log.warn('RemoteCube starting')
reactor.run()
Option().log.warn('RemoteCube gracefully halting')
print 'Bye'

